package com.ywu.application.standard.dataDict.service;

import com.ywu.boot.context.YwuContextHolder;
import com.ywu.common.entity.PageList;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.application.standard.dataDict.data.DataDictRepository;
import com.ywu.application.standard.dataDict.dto.DataDictDto;
import com.ywu.application.standard.dataDict.entity.DataDictEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName DataDictService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/7/6 21:19
 * @Version 1.0
 **/
@Service
public class DataDictService {
    @Autowired
    private DataDictRepository dataDictRepository;

    /**
    * @Author GroundDemo
    * @Description 分页查询数据字典列表
    * @Date 21:27 2024/7/6
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryDataDictListByPage(DataDictDto dataDictDto) {
        // 设置查询的租户ID
        dataDictDto.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        // 查询分页数量
        int count = dataDictRepository.queryPageCount(dataDictDto);
        // 设置分页参数
        PageService.execPageStartAndEnd(dataDictDto.getPageInfo());
        // 查询分页数据
        List<DataDictEntity> dataDictEntities = dataDictRepository.queryPageList(dataDictDto);
        // 构建分页对象
        PageList<DataDictEntity> dataDictEntityPageList = new PageList<>(dataDictDto.getPageInfo().getPageIndex(), dataDictDto.getPageInfo().getPageSize(),
                count, dataDictEntities);
        return CommonResult.success(dataDictEntityPageList);
    }

    /**
    * @Author GroundDemo
    * @Description 添加数据字典
    * @Date 21:35 2024/7/6
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> addDataDictInfo(DataDictDto dataDictDto) {
        // 查询键是否存在
        DataDictEntity searchEntity = new DataDictEntity();
        searchEntity.setName(dataDictDto.getName());
        searchEntity.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        DataDictEntity entity = dataDictRepository.getEntity(searchEntity);
        if (Objects.nonNull(entity)) {
            return CommonResult.error().setErrorCode("dict.key.is.exists")
                    .setMessage("键已存在");
        }
        // 构建entity对象
        DataDictEntity dataDictEntity = new DataDictEntity();
        BeanUtils.copyProperties(dataDictDto, dataDictEntity);
        // 设置创建人等信息，租户等信息
        dataDictEntity.createInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        dataDictEntity.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        // 执行sql
        dataDictRepository.addDataDictInfo(dataDictEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 更新数据字典
    * @Date 21:39 2024/7/6
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateDataDictInfo(DataDictDto dataDictDto) {
        // 判断ID是否存在
        if (Objects.isNull(dataDictDto.getId())) {
            return CommonResult.error().setErrorCode("id.is.null").setMessage("ID为空");
        }
        DataDictEntity searchEntity = new DataDictEntity();
        searchEntity.setId(dataDictDto.getId());
        DataDictEntity entity = dataDictRepository.getEntity(searchEntity);
        if (Objects.isNull(entity)) {
            return CommonResult.error().setErrorCode("id.is.not.exists").setMessage("ID不存在");
        }
        // 判断键是否存在
        searchEntity.setId(null);
        searchEntity.setName(dataDictDto.getName());
        searchEntity.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        List<DataDictEntity> entityList = dataDictRepository.getEntityList(searchEntity);
        List<DataDictEntity> collect = entityList.stream().filter(res -> !Objects.equals(res.getId(), dataDictDto.getId()))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            return CommonResult.error().setErrorCode("dict.key.is.exists")
                    .setMessage("键已存在");
        }
        // 构建Entity对象
        DataDictEntity dataDictEntity = new DataDictEntity();
        BeanUtils.copyProperties(dataDictDto, dataDictEntity);
        // 设置更新时间、更新人等信息
        dataDictEntity.updateInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        // 执行sql
        dataDictRepository.updateDataDictInfo(dataDictEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 删除数据字典
    * @Date 21:43 2024/7/6
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteDataDictInfo(DataDictDto dataDictDto) {
        // 构建entity对象
        DataDictEntity dataDictEntity = new DataDictEntity();
        // 设置ID
        dataDictEntity.setId(dataDictDto.getId());
        // 执行sql
        dataDictRepository.deleteDataDictInfoById(dataDictEntity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 更新是否租户共享的状态
    * @Date 9:05 2024/9/21
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> updateIsShare(DataDictDto dataDictDto) {
        // 判断ID是否存在
        DataDictEntity searchEntity = new DataDictEntity();
        searchEntity.setId(dataDictDto.getId());
        DataDictEntity queryEntity = dataDictRepository.getEntity(searchEntity);
        if (Objects.isNull(queryEntity)) {
            return CommonResult.error().setErrorCode("id.is.not.exists").setMessage("ID不存在");
        }
        // 根据ID修改共享状态
        DataDictEntity entity = new DataDictEntity();
        BeanUtils.copyProperties(dataDictDto, entity);
        entity.updateInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        dataDictRepository.updateIsShare(entity);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 查询数据字典
    * @Date 9:11 2024/9/21
    * @Param [dataDictDto]
    * @return com.ywu.common.result.CommonResult<com.ywu.data.dict.standard.entity.DataDictEntity>
    **/
    public CommonResult<DataDictEntity> queryDataDict(DataDictDto dataDictDto) {
        DataDictEntity dataDictEntity = new DataDictEntity();
        BeanUtils.copyProperties(dataDictDto, dataDictEntity);
        // 设置租户ID
        if (Objects.nonNull(YwuContextHolder.getCurrentContext().getYwuContextTenant()) &&
            StringUtils.isNotEmpty(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId())) {
            String tenantId = YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId();
            dataDictEntity.setTenantId(tenantId);
        }
        // 先根据租户ID查询键值，如果查询的结果为空，则查询共享的数据
        DataDictEntity entity = dataDictRepository.getEntity(dataDictEntity);
        if (Objects.isNull(entity)) {
            entity = dataDictRepository.getEntityByShare(dataDictEntity);
        }
        return CommonResult.success(entity);
    }
}
